#include "stdafx.h"
#include "BasicCaretMgr.h"
#include "BasicSkinWidget.h"

namespace BasicSkinView
{

	

	CBasicCaretMgr::CBasicCaretMgr( CBasicSkinWidget* pWidget )
		:m_pWidget(pWidget)
		,m_bOnCaret(false)
		,m_bVisible(false)
		,m_nHideLevel(0)
		,m_cxCaret(0)
		,m_cyCaret(0)
		,m_hBitmap(NULL)
		,m_xCaret(-100000)
		,m_yCaret(-100000)
		,m_pFocusView(NULL)
	{

	}

	CBasicCaretMgr::~CBasicCaretMgr()
	{
	}

	bool CBasicCaretMgr::Mgr_IsCanDrawCaret()
	{
		return m_bVisible;
	}

	bool CBasicCaretMgr::Mgr_CreateCaret( HBITMAP hBitmap,int cx, int cy )
	{
		m_bOnCaret = true;
		m_bVisible = false;
		m_nHideLevel = 1;
		m_cxCaret = cx;
		m_cyCaret = cy;
		m_hBitmap = hBitmap;
		return true;
	}

	void CBasicCaretMgr::Mgr_SetCaretPos( CBasicSkinView* pView,int x,int y )
	{
		m_pFocusView = pView;
		//If the caret is visible, turn it off while we move it.
		bool bVisible = m_bVisible;

		if(m_bVisible)
			Mgr_InvertCaret();

		m_xCaret = x;
		m_yCaret = y;
		m_bOnCaret = true;

		//Draw it immediately now if the hide level permits it
		m_bVisible = false;

		if(m_nHideLevel == 0)
		{
			//m_bVisible = true;
			m_bVisible = bVisible;
			if(bVisible)
				Mgr_InvertCaret();
		}
	}

	void CBasicCaretMgr::Mgr_ShowCaret()
	{
		/*
		 * If the caret hide level is aleady 0 (meaning it's ok to show) and the
		 * caret is not physically on, try to invert now if it's turned on.
		 */
		m_pFocusView = NULL;
		if(m_nHideLevel == 0)
		{
			if(!m_bVisible)
			{
				if((m_bVisible = m_bOnCaret) != 0)
					Mgr_InvertCaret();
			}
			return;
		}
		/*
		 * Adjust the hide caret hide count.  If we hit 0, we can show the
		 * caret.  Try to invert it if it's turned on.
		 */
		if(--m_nHideLevel == 0)
		{
			if((m_bVisible = m_bOnCaret) != 0)
			{
				Mgr_InvertCaret();
			}
		}
	}

	void CBasicCaretMgr::Mgr_InvertCaret()
	{
		if(m_pWidget)
		{
			m_pWidget->BsInvertCaret();
		}
	}

	void CBasicCaretMgr::Mgr_HideCaret()
	{
		/*
		 * If the caret is physically visible, invert it to turn off the bits.
		 * Adjust the hide count upwards to remember this hide level.
		 */
		if(m_bVisible)
			Mgr_InvertCaret();

		m_bVisible = false;
		m_nHideLevel++;
	}

	void CBasicCaretMgr::Mgr_DestroyCaret()
	{
		Mgr_HideCaret();
		m_nHideLevel = 0;
		m_pFocusView = NULL;
	}

	void CBasicCaretMgr::Mgr_OnBlinkProc()
	{
		m_bOnCaret ^= 1;
		if(m_nHideLevel == 0)
		{
			m_bVisible ^= 1;
			Mgr_InvertCaret();
		}
	}
}